<?php

namespace app\admin\controller;

use think\exception\ValidateException;
use app\model\Users;
use app\model\UsersSessions;
use app\model\UsersRoles;

class UsersController extends Base
{

	function index()
	{

		$page = input('post.page', 1, 'intval');
		$keyword = trim(input('post.keyword', '', 'serach_in'));
		$sex = input('post.sex', '', 'serach_in');
		$status = input('post.status', '', 'serach_in');
		$role_id = input('post.role_id', '', 'serach_in');

		$where = [];

		if (!empty($sex)) {
			$where['sex'] = $sex;
		}
		if ($status !== '') {
			$where['status'] = $status;
		}

		if (!empty($role_id)) {
			$where['role_id'] = $role_id;
		}

		$field = 'id,title,username,sex,touxiang,remark,status,create_time';

		$withJoin = [
			'roles' => explode(',', 'title'),
		];

		$query = Users::where($where)->field($field)->withJoin($withJoin, 'left');

		if (!empty($keyword)) {
			$query->where('users.title|users.username', 'like', '%' . $keyword . '%');
		}

		$res = $query->order('id desc')
			->paginate(getpage())
			->toArray();
		$data['data'] = $res;

		if ($page == 1) {
			$data['field_data']['role_ids'] = UsersRoles::getallarray();
		}
		return $this->json($data);
	}

	/*
 	* @Description  添加
 	*/
	public function add()
	{
		$postField = 'title,username,password,sex,touxiang,role_id,remark,status,create_time';
		$data = $this->request->only(explode(',', $postField), 'post', null);

		$data["salt"] = substr(md5(uniqid()), 8, 8);
		$data['create_time'] = time();
		$data["update_time"] = time();

		$data['password'] = pass_hash($data['password'], $data["salt"], $data["create_time"]);

		try {
			$res = Users::create($data);
		} catch (\Exception $e) {
			throw new ValidateException($e->getMessage());
		}
		return $this->json(['msg' => '添加成功', 'data' => $res->id]);
	}

	public function update()
	{
		$id = $this->request->post('id');
		if (empty($id)) {
			return $this->add();
		} else {
			$postField = 'id,title,username,password,sex,touxiang,role_id,remark,status,create_time';

			$data = $this->request->only(explode(',', $postField), 'post', null);
			$data["update_time"] = time();
			if (!empty($data['password'])) {
				$userdata = Users::field('id,title,create_time')->find($id);
				$data["salt"] = substr(md5(uniqid()), 8, 8);

				$data['password'] = pass_hash($data['password'], $data["salt"], $userdata["create_time"]);
			}
			try {
				Users::update($data);
			} catch (\Exception $e) {
				throw new ValidateException($e->getMessage());
			}
			return $this->json(['msg' => '修改成功']);
		}
	}

	function getUpdateInfo()
	{
		$id =  $this->request->post('id', '', 'serach_in');
		if (!$id) throw new ValidateException('参数错误');
		$field = 'id,title,username,touxiang,sex,role_id,remark,status,create_time';
		$res = Users::field($field)->find($id);
		return $this->json(['data' => $res]);
	}

	/*
 	* @Description  修改排序开关
 	*/
	function updateExt()
	{
		$postField = 'id,status';
		$data = $this->request->only(explode(',', $postField), 'post', null);
		if (!$data['id']) throw new ValidateException('参数错误');
		Users::update($data);
		return $this->json(['msg' => '操作成功']);
	}

	/*start*/
	/*
 	* @Description  删除
 	*/
	function delete()
	{
		$idx =  $this->request->post('id', '', 'serach_in');
		if ($idx == 1) {
			throw new ValidateException('超级用户禁止删除');
		}
		if (!$idx) throw new ValidateException('参数错误');
		Users::destroy(['id' => explode(',', $idx)], true);
		return $this->json(['msg' => '操作成功']);
	}

	/*
 	* @Description  禁用
 	*/
	public function forbidden()
	{
		$idx = $this->request->post('id', '', 'serach_in');
		if (empty($idx)) throw new ValidateException('参数错误');

		$data['status'] = '0';
		$res = Users::field('status')
			->where(['id' => explode(',', $idx)])
			->update($data);
		return $this->json(['msg' => '操作成功']);
	}

	/*
 	* @Description  导入
 	*/
	public function importData()
	{
		$data = $this->request->post();
		$list = [];

		foreach ($data as $key => $val) {
			$list[$key]['username'] = $val['用户名'];
			$list[$key]['title'] = $val['姓名'];
			$list[$key]['sex'] = getValByKey($val['性别'], '[{"key":"男","val":"1","label_color":""},{"key":"女","val":"2","label_color":""}]');
			$list[$key]['touxiang'] = $val['头像'];
			$list[$key]['mobile'] = $val['手机号'];
			$list[$key]['email'] = $val['邮箱'];
			$list[$key]['password'] = $val['密码'] ? md5($val['密码']) : '';
			$list[$key]['points'] = $val['积分'];
			$list[$key]['status'] = getValByKey($val['状态'], '[{"key":"开启","val":"1"},{"key":"关闭","val":"0"}]');
			$list[$key]['create_time'] = time();
		}
		(new Users)->saveAll($list);
		return $this->json(['msg' => '操作成功']);
	}

	function dumpdata()
	{
		$page = $this->request->post('page', 1, 'intval');
		$limit = config('my.dumpsize') ? config('my.dumpsize') : 1000;

		$keyword = trim(input('post.keyword', '', 'serach_in'));
		$sex = input('post.sex', '', 'serach_in');
		$status = input('post.status', '', 'serach_in');
		$role_id = input('post.role_id', '', 'serach_in');

		$where = [];

		if (!empty($sex)) {
			$where['sex'] = $sex;
		}
		if ($status !== '') {
			$where['status'] = $status;
		}

		if (!empty($role_id)) {
			$where['role_id'] = $role_id;
		}

		$field = 'id,username,title,sex,touxiang,mobile,email,password,points,status,create_time';

		$withJoin = [
			'roles' => explode(',', 'title'),
		];

		$query = Users::where($where)->field($field)->withJoin($withJoin, 'left');

		if (!empty($keyword)) {
			$query->where('users.title|users.username', 'like', '%' . $keyword . '%');
		}

		$count = $query->count();

		$res = $query->order('id desc')
			->limit(($page - 1) * $limit, $limit)
			->select()
			->toArray();

		foreach ($res as $key => $val) {
			$res[$key]['sex'] = getItemVal($val['sex'], '[{"key":"男","val":"1","label_color":""},{"key":"女","val":"2","label_color":""}]');
			$res[$key]['status'] = getItemVal($val['status'], '[{"key":"开启","val":"1"},{"key":"关闭","val":"0"}]');
			$res[$key]['create_time'] = date('Y-m-d H:i:s', $val['create_time']);
		}

		$data['header'] = explode(',', '编号,用户名,姓名,性别,头像,手机号,邮箱,密码,积分,状态,注册时间');
		$data['percentage'] = ceil($page * 100 / ceil($count / $limit));
		$data['filename'] = '用户数据.' . config('my.dump_extension');
		$data['data'] = $res;
		return $this->json($data);
	}

	//获取用户信息 菜单信息 以及菜单对应的组件
	public function getUserInfo()
	{
		if (!$this->userInfo['id']) {
			throw new ValidateException('用户Id不存在');
		}

		$userInfo = Users::field('role_id,username,touxiang,qianming')->where('id', $this->userInfo['id'])->find();
		if (!$userInfo) {
			throw new ValidateException('用户信息不存在');
		}else{
			$userInfo = $userInfo->toArray();
		}

		$rolesInfo = UsersRoles::where('id', $userInfo['role_id'])->find();

		if(empty($rolesInfo)){
			$rolesInfo = [];
		}else{
			$rolesInfo = $rolesInfo->toArray();
		}

		$menu = $this->getMyMenus($rolesInfo, $this->getTotalMenus());

		$components = $this->getComponents($menu, $userInfo['role_id']);

		$userInfo['sys_title']  = config('sysconfig.sys_title');
		$userInfo['logo'] = config('sysconfig.logo');

		$data['menu'] = $menu;
		$data['components'] = $components;
		$data['actions'] = explode(',', $rolesInfo['access']);
		$userInfo['roles'] = $components;
		$userInfo['avatar'] = $userInfo['touxiang'];
		$data['data'] = $userInfo;

		return $this->json($data);
	}

	//获取当前角色的菜单
	private function getMyMenus($rolesInfo, $totalMenus)
	{
		if ($rolesInfo['id'] == 1) {
			return $totalMenus;
		}
		foreach ($totalMenus as $key => $val) {
			if (in_array($val['name'], explode(',', $rolesInfo['access']))) {
				$tree[] = array_merge($val, ['children' => $this->getMyMenus($rolesInfo, $val['children'])]);
			}
		}
		return array_values($tree);
	}

	//退出
	public function logout()
	{
		$token = $this->request->header('Authorization');
		UsersSessions::where('token', $token)->delete();
		return  $this->json(['msg' => '退出成功']);
	}

	/*
 	* @Description  重置密码
 	*/
	public function resetPwd()
	{
		$postField = 'id,password';
		$data = $this->request->only(explode(',', $postField), 'post', null);
		if (empty($data['id'])) throw new ValidateException('参数错误');
		if (empty($data['password'])) throw new ValidateException('密码不能为空');

		$userdata = Users::field('id,title,create_time')->find($data['id']);
		$data["salt"] = substr(md5(uniqid()), 8, 8);

		$data['password'] = pass_hash($data['password'], $data["salt"], $userdata["create_time"]);

		$res = Users::update($data);
		return $this->json(['msg' => '操作成功']);
	}

	function getField()
	{
		$data['role_ids'] = UsersRoles::getallarray();
		return $this->json(['data' => $data]);
	}
}
